package com.glela.common.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glela.common.model.sms.SMSAfterSaleApply;
import com.glela.common.model.sms.SMSVerifyCode;
import com.glela.common.model.sms.SMSVerifyCode.VerifyCodeType;
import com.glela.common.model.sms.SMSWalletDrawMoney;
import com.glela.common.model.sms.SmsTemplate;
import com.glela.common.model.sms.order.SMSNoticeDelivery;
import com.glela.common.model.sms.order.SMSSuccessOrderPayment;
import com.glela.common.service.SMSService;
import com.glela.common.util.HttpUtil;
import com.zls.commons.msg.SourceSys;
import com.zls.rabbitmq.service.SMSSenderService;
import com.zls.sms.jianzhou.SmsJianzhou;

@Service("SMSService")
public class SMSServiceImpl implements SMSService {
	private static Logger logger = LoggerFactory.getLogger(SMSServiceImpl.class);

	@Resource(name = "freemarker")
	private FreeMarkerConfigurer	freemarker;
	@Autowired
	private SMSSenderService		smsSenderService;

	private static final String					SEND_JIANZHOU	= "jianzhou";
	/** 模版路径对应关系集合 */
	private static final Map<String, String>	templatePathMap	= new HashMap<String, String>();

	@Override
	public Long afterSaleApply(SMSAfterSaleApply sms) {
		checkSms(sms);
		String msg = getTemplateString("/after_sales/notice_store_member_launch_after_sale.ftl", sms);
		if (StringUtils.isBlank(msg)) {
			throw new IllegalArgumentException("会员发起售后通知店主短信模版读取异常/after_sales/notice_store_member_launch_after_sale.ftl");
		}
		return sendJianZhou(false, sms.getMobile(), msg);
	}

	@Override
	public long walletDrawMoney(SMSWalletDrawMoney sms) {
		checkSms(sms);
		String msg = getTemplateString("/user/reminding_of_the_balance.ftl", sms);
		if (StringUtils.isBlank(msg)) {
			throw new IllegalArgumentException("读取会员申请提现提醒短信模版异常/user/reminding_of_the_balance.ftl");
		}
		return sendJianZhou(false, sms.getMobile(), msg);
	}

	@Override
	public long verifyCodeLogin(SMSVerifyCode sms) {
		checkSms(sms);
		return sendJianZhou(sms.isSync(), sms.getMobile(), "您的验证码是" + sms.getCode() + "【小铺来了】", false);
	}

	@Override
	public long verifyCodePwd(SMSVerifyCode sms, VerifyCodeType versionType) {
		checkSms(sms);
		String msg = "您正在" + versionType.getAlias() + "，验证码为" + sms.getCode() + "（切勿告知他人），30分钟内有效。如有问题请及时联系客服400-036-9090【小铺来了】";
		return sendJianZhou(sms.isSync(), sms.getMobile(), msg, false);
	}

	@Override
	public long successOrderPayment(SMSSuccessOrderPayment sms) {
		checkSms(sms);

		String msg = getTemplateString("/order/success_order_payment.ftl", sms);
		if (StringUtils.isBlank(msg)) {
			throw new IllegalArgumentException("订单支付成功短信模版读取异常/order/success_order_payment.ftl");
		}
		return sendJianZhou(sms.isSync(), sms.getMobile(), msg);
	}
	//	@Autowired
	//	RedisUtil redisUtil;

	@Override
	public long noticeDelivery(SMSNoticeDelivery sms) {
		checkSms(sms);
		//		//验证键值是否存在
		//		String key = "" + sms.getMobile() + ":order" + sms.getOrderSn();
		//		if (redisUtil.exists(key)) {
		//			return -1;
		//		} else {
		//			redisUtil.set(key, DateUtil.getNowSSS(), 24 * 60 * 60);
		//		}
		String msg = getTemplateString("/order/notice_delivery.ftl", sms);
		if (StringUtils.isBlank(msg)) {
			throw new IllegalArgumentException("订单发货短信模版读取异常/order/notice_delivery.ftl");
		}
		return sendJianZhou(sms.isSync(), sms.getMobile(), msg);
	}

	@Override
	public long sendMsgJianZhou(boolean sync, String mobile, String msg) {
		return sendJianZhou(sync, mobile, msg);
	}

	/** 校验短信信息 */
	private void checkSms(SmsTemplate sms) {
		if (sms == null) {
			throw new NullPointerException("短信内容为空");
		}
		if (sms.checkMsg()) {
			logger.error("短信参数异常：{}", JSON.toJSONString(sms));
			throw new IllegalArgumentException("短信参数异常，无法发送短信");
		}
	}

	/** 建周通道发送 */
	private long sendJianZhou(boolean sync, String mobile, String msg) {
		return sendJianZhou(sync, mobile, msg, true);
	}

	private long sendJianZhou(boolean sync, String mobile, String msg, boolean isBatch) {
		if (sync) {
			return sendSMSJianZhou(mobile, msg);
		}
		return lpush(mobile, msg, SEND_JIANZHOU, isBatch);
	}

	/**
	 * <dl>
	 * <dt>异步发送短信</dt>
	 * </dl>
	 * @param queueMsgSMS
	 * @return long
	 * @author zls
	 * @date 2018年3月9日 下午1:14:29
	 */
	private long lpush(String mobile, String msg, String sendTo, boolean isBatch) {
		//		try {
		//			Long lpush = QueueRedisUtil.lpush(queueMsgSMS);
		//			return lpush == null ? -1 : lpush;
		//		} catch (Exception e) {
		//			logger.error("redis连接异常:{}", e.getMessage());
		//			return sendSMSJianZhou(queueMsgSMS);
		//		}
		SmsJianzhou smsJianzhou = new SmsJianzhou(SourceSys.XIAOPU);
		smsJianzhou.setMsg(msg);
		if (isBatch) {
			smsJianzhou.getMobiles().add(mobile);
		} else {
			smsJianzhou.setReceiverMobile(mobile);
		}
		if (smsJianzhou.checkInfo()) {
			logger.error("发送短信格式错误：{}-{}:{}", mobile, msg, JSONObject.toJSONString(smsJianzhou));
			return -1;
		}
		if (StringUtils.equals(SEND_JIANZHOU, sendTo)) {
			boolean convertAndSend = smsSenderService.convertAndSend(smsJianzhou);
			if (!convertAndSend) {//如果异步消息发送失败，走直连发送
				return sendSMSJianZhou(mobile, msg);
			}
			return 1;
		} else {
			logger.error("短信发送失败：未知的短信发送通道{}-{}-{}", sendTo, mobile, msg);
			throw new NullPointerException("短信发送失败：未知的短信发送通道");
		}
	}

	private long sendSMSJianZhou(String mobile, String msg) {
		Map<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("account", "sdk_xiaozhuang");
		hashMap.put("password", "hvf2v8xh");
		hashMap.put("userTaskID", 666666);
		hashMap.put("destmobile", mobile);
		//		hashMap.put("msgText", URLEncoder.encode(sms.getMsg(), "UTF-8"));
		hashMap.put("msgText", msg);
		//		hashMap.put("sendDateTime", value);
		//		hashMap.put("ext", value);
		//		logger.warn("直连建周发送短信：{}", JSON.toJSONString(hashMap));
		try {
			HttpUtil.post("http://www.jianzhou.sh.cn/JianzhouSMSWSServer/http/sendBatchMessage", hashMap);
			return 1;
		} catch (Exception e) {
			logger.error("直连建周发送短信失败{}", e.getMessage());
		}
		return -1;
	}

	/** 获取模版路径 */
	private String getTemplatePath(String name) {
		String path = MapUtils.getString(templatePathMap, name, null);
		if (path == null) {
			path = "/sms" + name;
			templatePathMap.put(name, path);
		}
		return path;
	}

	/** 根据模版动态生成文本 */
	private String getTemplateString(String templateName, Object model) {
		try {
			return FreeMarkerTemplateUtils.processTemplateIntoString(freemarker.getConfiguration().getTemplate(getTemplatePath(templateName)), model);
		} catch (Exception e) {
			logger.error("读取短信模版异常：{}", e.getMessage(), e);
		}
		return null;
	}
}